<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android," />





  <link rel="alternate" href="/atom.xml" title="结网之路" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="本章介绍了如何写一个双版面 fragment 的布局，并对符合要求的设备进行适配，还介绍了回调接口的使用。GitHub 地址：完成17章

对平板设备来说，使用主从用户界面将会得到更好的体验，在这章我们将对其使用，传递数据的方式进行探究。
1. 增加布局灵活性要实现双版面的布局，需要完成如下任务：

修改 SingleFragmentActivity，使其不再硬编码实例化布局
创建包含两个 fr">
<meta property="og:type" content="article">
<meta property="og:title" content="Android编程权威指南（第二版）学习笔记（十七）—— 第17章 Master-Detail 用户界面">
<meta property="og:url" content="https://kniost.github.io/2017-01-15-cj0ajvouv000r1js64b00vv1f/index.html">
<meta property="og:site_name" content="结网之路">
<meta property="og:description" content="本章介绍了如何写一个双版面 fragment 的布局，并对符合要求的设备进行适配，还介绍了回调接口的使用。GitHub 地址：完成17章

对平板设备来说，使用主从用户界面将会得到更好的体验，在这章我们将对其使用，传递数据的方式进行探究。
1. 增加布局灵活性要实现双版面的布局，需要完成如下任务：

修改 SingleFragmentActivity，使其不再硬编码实例化布局
创建包含两个 fr">
<meta property="og:updated_time" content="2017-03-14T06:47:59.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android编程权威指南（第二版）学习笔记（十七）—— 第17章 Master-Detail 用户界面">
<meta name="twitter:description" content="本章介绍了如何写一个双版面 fragment 的布局，并对符合要求的设备进行适配，还介绍了回调接口的使用。GitHub 地址：完成17章

对平板设备来说，使用主从用户界面将会得到更好的体验，在这章我们将对其使用，传递数据的方式进行探究。
1. 增加布局灵活性要实现双版面的布局，需要完成如下任务：

修改 SingleFragmentActivity，使其不再硬编码实例化布局
创建包含两个 fr">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://kniost.github.io/2017-01-15-cj0ajvouv000r1js64b00vv1f/"/>





  <title> Android编程权威指南（第二版）学习笔记（十七）—— 第17章 Master-Detail 用户界面 | 结网之路 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">结网之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">临渊羡鱼，不如退而结网</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://kniost.github.io/2017-01-15-cj0ajvouv000r1js64b00vv1f/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="kniost">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="结网之路">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Android编程权威指南（第二版）学习笔记（十七）—— 第17章 Master-Detail 用户界面
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-01-15T18:02:10+08:00">
                2017-01-15
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android编程权威指南学习笔记/" itemprop="url" rel="index">
                    <span itemprop="name">Android编程权威指南学习笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017-01-15-cj0ajvouv000r1js64b00vv1f/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2017-01-15-cj0ajvouv000r1js64b00vv1f/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>本章介绍了如何写一个双版面 fragment 的布局，并对符合要求的设备进行适配，还介绍了回调接口的使用。<br>GitHub 地址：<br><a href="https://github.com/kniost/Android-Programming-Big-Nerd-Ranch-Guide-2nd/commit/6b11d46262c10d7a6a143e2e2be225bc99851852" target="_blank" rel="external">完成17章</a></p>
</blockquote>
<p>对平板设备来说，使用主从用户界面将会得到更好的体验，在这章我们将对其使用，传递数据的方式进行探究。</p>
<h1 id="1-增加布局灵活性"><a href="#1-增加布局灵活性" class="headerlink" title="1. 增加布局灵活性"></a>1. 增加布局灵活性</h1><p>要实现双版面的布局，需要完成如下任务：</p>
<ol>
<li>修改 SingleFragmentActivity，使其不再硬编码实例化布局</li>
<li>创建包含两个 fragment 容器的布局</li>
<li>修改 CrimeListActivity，实现在手机设备上实例化单版面布局，在平板设备上实例化双版面布局</li>
</ol>
<h2 id="1-1-修改抽象类-SingleFragmentActivity"><a href="#1-1-修改抽象类-SingleFragmentActivity" class="headerlink" title="1.1 修改抽象类 SingleFragmentActivity"></a>1.1 修改抽象类 SingleFragmentActivity</h2><p>在其中加入一个 protected 方法，返回 activity 需要的 ResId，这样对于继承 SingleFragmentActivity 的 activity 可以重写该函数以返回自己需要的 ResId。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@LayoutRes</span></div><div class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">int</span> <span class="title">getLayoutResId</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> R.layout.activity_fragment;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="1-2-使用别名资源"><a href="#1-2-使用别名资源" class="headerlink" title="1.2 使用别名资源"></a>1.2 使用别名资源</h2><p>我们想让最小屏幕宽度 600dp 的设备使用双版面界面，其他的使用单版面界面，那么对于不同的设备，使用的布局就不同。要让不同的设备使用不同的布局资源，有两种方法：</p>
<ol>
<li>让 res/layout/目录中的文件使用资源修饰符。如果想使用<code>activity_masterdetail.xml</code>布局文件， 就需要将<code>activity_fragment.xml</code>的内容复制到<code>res/layout/activity_masterdetail.xml</code>中，将<code>activity_twopane.xml</code>的内容复制到<code>res/layout-sw600dp/activity_masterdetail.xml</code>中。这样做最明显的缺点就是数据冗余，因为每个布局文件都要复制一份。</li>
<li><p>使用别名资源。别名资源是一种指向其他资源的特殊资源。它存放在 res/values/目录下，并按照约定定义在 refs.xml 文件中。比如在默认的 values 文件夹下面新建一个 refs.xml，然后写入代码：</p>
 <figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">&lt;?xml version="1.0" encoding="utf-8"?&gt;</div><div class="line"><span class="tag">&lt;<span class="name">resources</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">item</span> <span class="attr">name</span>=<span class="string">"activity_masterdetail"</span> <span class="attr">type</span>=<span class="string">"layout"</span>&gt;</span>@layout/activity_fragment<span class="tag">&lt;/<span class="name">item</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">resources</span>&gt;</span></div></pre></td></tr></table></figure>
<p> 再新建一个最小宽度600dp 的 refs.xml(即在 values-sw600dp 目录下)，写入双版面的 layout 资源：</p>
 <figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">&lt;?xml version="1.0" encoding="utf-8"?&gt;</div><div class="line"><span class="tag">&lt;<span class="name">resources</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">item</span> <span class="attr">name</span>=<span class="string">"activity_masterdetail"</span> <span class="attr">type</span>=<span class="string">"layout"</span>&gt;</span>@layout/activity_twopane<span class="tag">&lt;/<span class="name">item</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">resources</span>&gt;</span></div></pre></td></tr></table></figure>
<p> 这样，在 CrimeListActivity 中只要引用 <code>R.layout.activity_masterdetail</code> 即可</p>
</li>
</ol>
<h1 id="2-Activity：Fragment-的托管者"><a href="#2-Activity：Fragment-的托管者" class="headerlink" title="2. Activity：Fragment 的托管者"></a>2. Activity：Fragment 的托管者</h1><p>为了保证 fragment 的独立性，即不需要了解其托管者的工作，但要想在 fragment 生命周期没有结束的时候传递数据出去，就要使用回调接口。</p>
<blockquote>
<p>回调就相当于一个委托，首先 fragment 自己定义回调的接口，托管的 acitivity 来实现这个接口，接着 fragment 需要持有实现了自己定义接口的对象，以便自己可以实时调用。</p>
<p>对于一个回调接口而言，fragment 只要求实现这个接口的类在函数里要做的是什么，却不知道实现类到底会做什么，每个实现类有自己的方法来实现。</p>
<h1 id="2-1-CrimeListFragment-的回调接口"><a href="#2-1-CrimeListFragment-的回调接口" class="headerlink" title="2.1 CrimeListFragment 的回调接口"></a>2.1 CrimeListFragment 的回调接口</h1><p>对于 CrimeListFragment，其所能响应的就是点击列表中的某一项，那么它的回调接口定义如下：</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Callbacks</span> </span>&#123;</div><div class="line">	<span class="function"><span class="keyword">void</span> <span class="title">onCrimeSelected</span><span class="params">(Crime crime)</span></span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>然后应该在需要托管的 Activity 中实现该接口，在这里是 CrimeListActivity：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 省略 implement 以节约版面</span></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCrimeSelected</span><span class="params">(Crime crime)</span> </span>&#123;</div><div class="line">	<span class="comment">// 如果发现布局里没有包含详情 fragment 容器的 id，</span></div><div class="line">	<span class="comment">// 就启动单独的 activity 用于显示详情</span></div><div class="line">    <span class="keyword">if</span> (findViewById(R.id.detail_fragment_container) == <span class="keyword">null</span>) &#123;</div><div class="line">        Intent intent = CrimePagerActivity.newIntent(<span class="keyword">this</span>, crime.getId());</div><div class="line">        startActivity(intent);</div><div class="line">    &#125; <span class="keyword">else</span> &#123;</div><div class="line">    <span class="comment">// 否则就将 detail 页面放到 fragment 容器中</span></div><div class="line">        Fragment newDetail = CrimeFragment.newInstance(crime.getId());</div><div class="line"></div><div class="line">        getSupportFragmentManager().beginTransaction()</div><div class="line">                .replace(R.id.detail_fragment_container, newDetail)</div><div class="line">                .commit();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>在 CrimeListFragment 中持有实现接口的 activity 的引用，然后在生命周期末去除引用以便内存的回收</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// CrimeListFragment</span></div><div class="line"><span class="keyword">private</span> Callbacks mCallbacks;</div><div class="line"></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onAttach</span><span class="params">(Context context)</span> </span>&#123;</div><div class="line">    <span class="keyword">super</span>.onAttach(context);</div><div class="line">    mCallbacks = (Callbacks) context;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 中间的函数……</span></div><div class="line"></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onDetach</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">super</span>.onDetach();</div><div class="line">    mCallbacks = <span class="keyword">null</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>最后修改 onClick 事件，调用 mCallbacks.onCrimeSelected(Crime crime) 即可。这样以后，在双版面视图中点击列表中的某一项，在详情版面中就会显示相应的信息。</p>
<p>但是有一个问题，那就是在详情页（CrimeFragment）更改信息，在列表页没有任何响应，因为 CrimeListFragment 不会暂停，所以也就不会刷新，所以下一步要在 CrimeFragment 中定义回调接口， 让托管 activity 去更新 CrimeListFragment。</p>
<h2 id="2-2-CrimeFragment-的回调接口"><a href="#2-2-CrimeFragment-的回调接口" class="headerlink" title="2.2 CrimeFragment 的回调接口"></a>2.2 CrimeFragment 的回调接口</h2><p>首先定义回调接口，这里想让托管者做的就是在 Crime 详情进行更新时更新列表</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// CrimeFragment</span></div><div class="line"><span class="keyword">private</span> Callbacks mCallbacks;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Callbacks</span> </span>&#123;</div><div class="line">	<span class="function"><span class="keyword">void</span> <span class="title">onCrimeUpdated</span><span class="params">(Crime crime)</span></span>;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onAttach</span><span class="params">(Context context)</span> </span>&#123;</div><div class="line">    <span class="keyword">super</span>.onAttach(context);</div><div class="line">    mCallbacks = (Callbacks) context;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 中间的函数……</span></div><div class="line"></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onDetach</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">super</span>.onDetach();</div><div class="line">    mCallbacks = <span class="keyword">null</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>在 CrimeListActivity 中实现该接口：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCrimeUpdated</span><span class="params">(Crime crime)</span> </span>&#123;</div><div class="line">    CrimeListFragment listFragment = (CrimeListFragment)</div><div class="line">            getSupportFragmentManager()</div><div class="line">                    .findFragmentById(R.id.fragment_container);</div><div class="line">    listFragment.updateUI();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>由于只要托管 CrimeFragment 的 activity 都应该实现其回调接口，所以在 CrimePagerActivity 中提供一个空的接口实现</p>
<p>之后在每次数据发生更改时都调用 <code>mCallbacks.onCrimeUpdated(mCrime);</code>即可。书上将更新模型层也放到了一起。</p>
<h1 id="3-挑战的后遗症：删除-Crime"><a href="#3-挑战的后遗症：删除-Crime" class="headerlink" title="3. 挑战的后遗症：删除 Crime"></a>3. 挑战的后遗症：删除 Crime</h1><p>还记得我们在 ToolBar 那一章加入的挑战吗，就是删除一个 Crime，对于 CriminalIntent 这个应用来说，双版面和单版面的删除操作应该有着不同的结果，但这些行为在书上没有定义，所以我们再自己想一种解决方案，以便确立如何写接下来的补充程序。</p>
<ol>
<li>双版面的界面下，点击删除应该要让左边的列表中去掉删除的那一项，并且详情页也要改为已存在的某一项的详情，为了方便实现，我们在这里改为已存在的第一项。如果只有最后一项并且点击了删除，那么右边应该要变成空白。</li>
<li>单版面的界面下，点击删除就直接删去该条记录，然后结束 activity。</li>
</ol>
<p>在这里我在 CrimeFragment 的 Callbacks 接口中加入了 onCrimeDelete(Crime crime) 方法与 onCrimeAllDeleted(Crime crime) 方法，在 CrimeListActivity 中实现如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCrimeDeleted</span><span class="params">(Crime crime)</span> </span>&#123;</div><div class="line">	<span class="comment">// 如果只是删除了一个，而还有其他的 Crime 的话，</span></div><div class="line">	<span class="comment">// 就相当于选中一个 Crime，这里传过来的应该是第一个 Crime</span></div><div class="line">    onCrimeSelected(crime);</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCrimeAllDeleted</span><span class="params">(Crime crime)</span> </span>&#123;</div><div class="line">	<span class="comment">// 如果全部删除，就直接将该 fragment 移去</span></div><div class="line">    CrimeFragment fragment = (CrimeFragment)</div><div class="line">            getSupportFragmentManager()</div><div class="line">                    .findFragmentById(R.id.detail_fragment_container);</div><div class="line">    <span class="keyword">if</span> (fragment != <span class="keyword">null</span>) &#123;</div><div class="line">        getSupportFragmentManager()</div><div class="line">                .beginTransaction()</div><div class="line">                .remove(fragment)</div><div class="line">                .commit();</div><div class="line">    &#125;</div><div class="line">    <span class="comment">// 并且更新列表页</span></div><div class="line">    onCrimeUpdated(crime);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>在 CrimePagerActivity 中也要实现这两个方法，但是对于这个 activity 来说只要进行 finish() 即可。</p>
<p>在删除按钮的选中监听中：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">CrimeLab.get(getActivity()).deleteCrime(mCrime);</div><div class="line"><span class="keyword">if</span> (CrimeLab.get(getActivity()).getCrimes().isEmpty()) &#123;</div><div class="line">    mCallbacks.onCrimeAllDeleted(mCrime);</div><div class="line">&#125; <span class="keyword">else</span> &#123;</div><div class="line">    mCrime = CrimeLab.get(getActivity()).getCrimes().get(<span class="number">0</span>);</div><div class="line">    mCallbacks.onCrimeDeleted(mCrime); <span class="comment">// 这里相当于选中第一个</span></div><div class="line">    updateCrime(); <span class="comment">// 这里面升级了数据层并且更新了列表</span></div><div class="line">&#125;</div><div class="line"><span class="keyword">return</span> <span class="keyword">true</span>;</div></pre></td></tr></table></figure>
<p>整个程序就此完成啦~</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag"># Android</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017-01-12-cj0ajvouz00111js6krejdvpn/" rel="next" title="Android编程权威指南（第二版）学习笔记（十六）—— 第16章 使用 intent 拍照">
                <i class="fa fa-chevron-left"></i> Android编程权威指南（第二版）学习笔记（十六）—— 第16章 使用 intent 拍照
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017-01-21-cj0ajvov000151js6cxlggt6s/" rel="prev" title="Android编程权威指南（第二版）学习笔记（十八）—— 第18章 Assets">
                Android编程权威指南（第二版）学习笔记（十八）—— 第18章 Assets <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread"></div>
<script>

/**
*  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
*  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/
/*
var disqus_config = function () {
this.page.url = PAGE_URL;  // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
*/
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://kniost-comment-github.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
                                
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="kniost" />
          <p class="site-author-name" itemprop="name">kniost</p>
           
              <p class="site-description motion-element" itemprop="description">kniost 的成长与疑惑</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">31</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-增加布局灵活性"><span class="nav-text">1. 增加布局灵活性</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-1-修改抽象类-SingleFragmentActivity"><span class="nav-text">1.1 修改抽象类 SingleFragmentActivity</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-2-使用别名资源"><span class="nav-text">1.2 使用别名资源</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-Activity：Fragment-的托管者"><span class="nav-text">2. Activity：Fragment 的托管者</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-1-CrimeListFragment-的回调接口"><span class="nav-text">2.1 CrimeListFragment 的回调接口</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2-CrimeFragment-的回调接口"><span class="nav-text">2.2 CrimeFragment 的回调接口</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-挑战的后遗症：删除-Crime"><span class="nav-text">3. 挑战的后遗症：删除 Crime</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">kniost</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'kniost-comment-github';
      var disqus_identifier = '2017-01-15-cj0ajvouv000r1js64b00vv1f/';

      var disqus_title = "Android编程权威指南（第二版）学习笔记（十七）—— 第17章 Master-Detail 用户界面";


      function run_disqus_script(disqus_script) {
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');

      
        var disqus_config = function () {
            this.page.url = disqus_url;
            this.page.identifier = disqus_identifier;
            this.page.title = disqus_title;
        };
        run_disqus_script('embed.js');
      

    </script>
  










  
  

  

  

  

  


  

</body>
</html>
